package cn.yunhe.realms;

import cn.yunhe.entity.Emp;
import cn.yunhe.entity.Permission;
import cn.yunhe.service.EmpService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 葛森
 * <p>
 * 授权认证操作
 */

public class UserLoginRealm extends AuthorizingRealm {
    @Resource
    private EmpService empService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Emp emp= (Emp) principals.getPrimaryPrincipal();

        /*List<Permission> list1=emp.getRole().getPermissionSet();
        for (Permission p:list1) {
            System.out.println(p.getPname()+"===========");
        }*/

       Set<String> permissionSet=new HashSet<>();
        List<Permission> list=emp.getRole().getPermissionSet();
        if(!CollectionUtils.isEmpty(list)){
            for (Permission p:list) {
                permissionSet.add(p.getPname());
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         info.addRole(emp.getRole().getRname());
         info.addStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        String name = utoken.getUsername();
        Emp emp = new Emp();
        emp.setEmpName(name);
        emp = empService.Login(emp);
        AuthenticationInfo info = new SimpleAuthenticationInfo(emp, emp.getEmpPassword(), ByteSource.Util.bytes(name), getName());
        return info;
    }

    public EmpService getEmpService() {
        return empService;
    }

    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }


   /* public static void main(String[] args) {
        System.out.println(new SimpleHash("MD5","123",ByteSource.Util.bytes("葛森"),1024));
    }*/
}
